<?php
/**
 * Description: 检查退款详情
 *
 * @author      Eden
 * @datetime    2016/12/20 11:04
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Refundview_Model extends API_Model
{

    private $width = 320;
    private $height = 180;


    // 订单信息
    private $order = null;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function run($params = array())
    {
        $send['state'] = false;
        do {

            if (!$this->checkParams($params)) {
                $send['error'] = $this->getError();
                break;
            }

            if ($params['type'] == 'android') {
                $this->width = $this->width / 2;
                $this->height = $this->height / 2;
            }

            $res = $this->getDetail($params);
            if (!$res) {
                $send['error'] = $this->getError();
                break;
            }

            $send['state'] = true;
            $send['data'] = $res;

        } while(false);
        $this->output->send($send);
    }

    /**
     * 商品详情
     * @param array $params
     * @return array|bool
     */
    private function getDetail(Array $params)
    {
        $db = clone($this->db);
        $q = $db->get_where('user_order_goods', array('orderId' => $params['orderId']));
        $goodsIds = $q->result_array();
        if (empty($goodsIds)) {
            $this->setError('无商品订单');
            return false;
        }

        $orderItems = $ids = [];
        foreach($goodsIds as $g) {
            $ids[] = $g['goodsId'];
            $orderItems[$g['goodsId']] = $g;
        }

        $goods = $this->getGoods($ids, $orderItems);
        if (!$goods) {
            return false;
        }

        $refund = $this->getRefund($params);
        if (!$refund) {
            return false;
        }

        $order = $this->order;
        return array(
            'orderId' => intval($order['id']),
            'sn' => value($order, 'sn'),
            'totalPrice' => doubleval($order['totalPrice']),
            'goodsPrice' => doubleval($order['goodsPrice']),
            'expressPrice' => doubleval($order['expressPrice']),
            'voucher' => value($order, 'voucher', ''),
            'addressId' => intval($order['addressId']),
            'payMode' => value($order, 'payMode', 'online'),
            'payWay' => empty($order['payWay']) ? '' : ($order['payWay'] == 1 ? 'alipay' : 'wechat'),
            'created' => value($order, 'created'),
            'status' => value($order, 'status'),
            'message' => value($order, 'message', ''),
            'refundData' => $refund,
            'goods' => $goods,
        );
    }

    /**
     * 退款信息
     * @param array $params
     * @return array|bool
     */
    private function getRefund(Array $params)
    {
        $db = clone($this->db);
        $q = $db->get_where('user_order_refund', array('orderId' => $params['orderId'], 'userId' => $params['userId']));
        $row = $q->row_array();
        if (empty($row)) {
            $this->setError('该订单未申请退款');
            return false;
        }

        $status = array(
            0 => '退款中',     // 暂未处理
            1 => '退款中',
            6 => '已退款'
        );

        return array(
            'amount' => doubleval($row['refundAmount']),
            'case' => value($row, 'cause', ''),
            'remark' => value($row, 'remark', ''),
            'created' => value($row, 'created'),
            'handleTime' => value($row, 'handleTime'),
            'status' => !empty($status[$row['status']]) ? $status[$row['status']] : '处理中'
        );

    }

    /**
     * 订单商品
     * @param array $ids
     * @param array $orderItems
     * @return array|bool
     */
    private function getGoods(Array $ids, Array $orderItems)
    {
        $db = clone($this->db);
        $q = $db->select('g.id as goodsId, g.goodsName, g.baseId, g.thumb, g.liveUrl, g.expressWeight, g.status, g.streamId')
            ->from('base_goods as g')
            ->where_in('g.id', $ids)
            ->get();
        $rows = $q->result_array();
        if (empty($rows)) {
            $this->setError('无商品订单');
            return false;
        }

        $return = [];
        foreach($rows as $item) {
            $id = $item['goodsId'];
            $return[] = array(
                'goodsId' => intval($item['goodsId']),
                'goodsName' => value($item, 'goodsName', ''),
                'num' => (int) $orderItems[$id]['num'],
                'price' => doubleval($orderItems[$id]['price']),
                'baseId' => intval($item['baseId']),
                'thumb' => thumb($item['thumb'], $this->width, $this->height),
                'expressWeight' => doubleval($item['expressWeight']),
                'status' => $item['status'] == '1' ? 'onSale' : 'offSale',
                'isLive' => !empty($item['liveUrl']),
                'liveUrl' => value($item, 'liveUrl', '')
            );
        }
        return $return;
    }

    /**
     * 检查参数
     * @param array $params
     * @return bool
     */
    private function checkParams(Array $params)
    {
        if (empty($params['orderId']) || empty($params['userId']) || empty($params['sn'])) {
            $this->setError('参数错误');
            return false;
        }

        if (!$this->checkOrder($params)) {
            return false;
        }

        return true;
    }

    /**
     * 验证订单
     * @param array $params
     * @return bool
     */
    private function checkOrder($params = array())
    {
        $db = clone($this->db);
        $q = $db->get_where('user_order', array('id' => $params['orderId']));
        $row = $q->row_array();
        if (empty($row)) {
            $this->setError('无效订单');
            return false;
        }

        if ($row['sn'] != $params['sn'] || $row['userId'] != $params['userId']) {
            $this->setError('无效订单编号');
            return false;
        }

        if ($row['status'] != 'Refund') {
            $this->setError('非退款订单');
            return;
        }

        $this->order = $row;
        return true;
    }
}
